<?php
/**
 * Created by PhpStorm.
 * User: LFL
 * Date: 2010/5/25
 * Time: 16:02
 */
namespace backend\controllers;

use backend\models\StockTmp;
use Yii;
use yii\web\AdminController;
use backend\models\Warehouse;
use backend\models\Supplier;

class StockTmpController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'stock_tmp';

    //入库单列表
    public function actionReceipt()
    {
        //仓库
        $warehouse_where = ['useFlg' => 1];
        $warehouse = Warehouse::find()->where($warehouse_where)->select('id,warehouseName')->asArray()->all();
        return $this->render('receipt', ['pageFlg' => 0, 'warehouse' => $warehouse]);
    }

    //添加入库单||详情
    public function actionAddReceipt()
    {
        $data = Yii::$app->request->get();
        //仓库

        $pur = isset($data['pur']) ? 1 : 0;

        $warehouse_where = ['useFlg' => 1];
        $warehouse = Warehouse::find()->where($warehouse_where)->select('id,warehouseName')->asArray()->all();

        //供应商
        $supplier_where = ['useFlg' => 1];
        $supplier = Supplier::find()->where($supplier_where)->select('id,supplierName')->asArray()->all();

        $stock = null;
        if (isset($data['stockNo']) && !empty($data['stockNo'])) {
            $sql = "SELECT * FROM j_stock_tmp WHERE stockNo='" . $data['stockNo'] . "'";
            $stock = Yii::$app->db->createCommand($sql)->queryOne();
            if (!$stock) $this->error('未找到单据信息');
            $sql = "SELECT sd.*,ma.id as materielId,ma.materielName,ma.specDesc,ma.packDesc,ma.purchaseUnit,ma.orderUnit,
            ma.purchaseDay,ma.safeDay,ma.orderUnit,wh.warehouseName,sp.supplierName FROM j_stock_dtl_tmp sd
            INNER JOIN j_materiel ma ON sd.materielId=ma.id
            INNER JOIN j_supplier sp ON sd.supplierId=sp.id
            LEFT JOIN j_warehouse wh ON ma.warehouseId=wh.id WHERE sd.stockNo='" . $data['stockNo'] . "'";
            $stockDtl = Yii::$app->db->createCommand($sql)->queryAll();
            $stock['dtl'] = $stockDtl;

            if ($stock['purchaseOrderNo'] && !empty($stock['purchaseOrderNo'])) {
                $pur = 1;
            } else {
                $pur = 0;
            }

        }

        return $this->render('add-receipt', ['warehouse' => $warehouse, 'supplier' => $supplier, 'stock' => $stock, 'pur' => $pur]);
    }

    //添加损益单||详情
    public function actionAddRevise()
    {
        $data = Yii::$app->request->get();
        //仓库
        $warehouse_where = ['useFlg' => 1];
        $warehouse = Warehouse::find()->where($warehouse_where)->select('id,warehouseName')->asArray()->all();
        $stock = null;
        if (isset($data['stockNo']) && !empty($data['stockNo'])) {
            $sql = "SELECT * FROM j_stock_tmp WHERE stockNo='" . $data['stockNo'] . "'";
            $stock = Yii::$app->db->createCommand($sql)->queryOne();
            if (!$stock) $this->error('未找到单据信息');
            $sql = "SELECT ms.*,ma.id as materielId,ma.materielName,ma.specDesc,ma.packDesc,ma.purchaseUnit,ma.referPrice,
                    ma.orderUnit,wh.warehouseName,sp.supplierName,sd.stockId,sd.qty editQty,sd.dType 
                    FROM j_stock_dtl_tmp sd 
                    INNER JOIN j_materiel_stock ms ON ms.id=sd.stockId
                    INNER JOIN j_materiel ma ON sd.materielId=ma.id
                    INNER JOIN j_warehouse wh ON ms.warehouseId=wh.id
                    INNER JOIN j_supplier sp ON ms.supplierId=sp.id WHERE sd.stockNo='" . $data['stockNo'] . "'";
            $stockDtl = Yii::$app->db->createCommand($sql)->queryAll();
            $stock['dtl'] = $stockDtl;
        }
        return $this->render('add-revise', ['warehouse' => $warehouse, 'stock' => $stock]);
    }


    //ajax入库单、损益单
    public function actionGetList()
    {
        $data = Yii::$app->request->post();
        $sql = '';
        $sql_list = 'SELECT st.*,wh.warehouseName FROM j_stock_tmp st INNER JOIN j_warehouse wh ON st.warehouseId=wh.id ';
        $sql_count = 'SELECT COUNT(0) CNT FROM j_stock_tmp st INNER JOIN j_warehouse wh ON st.warehouseId=wh.id ';

        $pageFlg = isset($data['pageFlg']) ? $data['pageFlg'] : 0;
        $sql .= ' WHERE sType = ' . $pageFlg;

        //searchName,stockStatus,warehouseId,
        //[remark] => 1111
        //    [expecteDate] => 2018-07-25 - 2018-07-25
        //    [actualDate] => 2018-07-25 - 2018-07-25


        if (isset($data['stockNo']) && !empty($data['stockNo'])) {
            $sql .= ' And st.stockNo like "%' . $data['stockNo'] . '%"';
        }
        if (isset($data['searchName']) && !empty($data['searchName'])) {
            $sql .= " AND EXISTS (select 1 from j_stock_dtl_tmp sd inner join j_materiel ma on sd.materielId=ma.id where ma.materielName like '%".$data['searchName']."%' and sd.stockNo = st.stockNo)";
        }
        if (isset($data['stockStatus']) && is_array($data['stockStatus'])) {
            $sql .= ' And st.stockStatus IN(' . implode(',', $data['stockStatus']) . ')';
        }
        if (isset($data['warehouseId']) && is_array($data['warehouseId'])) {
            $sql .= ' And st.warehouseId IN(' . implode(',', $data['warehouseId']) . ')';
        }
        if (isset($data['expecteDate']) && !empty($data['expecteDate'])) {
            $expecteDate = explode(' - ',$data['expecteDate']);
            $sql .= " AND st.expecteDate>='".$expecteDate[0]."' AND st.expecteDate <='".$expecteDate[1]." 23:59:59'";
        }
        if (isset($data['actualDate']) && !empty($data['actualDate'])) {
            $actualDate = explode(' - ',$data['actualDate']);
            $sql .= " AND st.actualDate>='".$actualDate[0]."' AND st.actualDate <='".$actualDate[1]." 23:59:59'";
        }
        if (isset($data['remark']) && !empty($data['remark'])) {
            $sql .= ' And st.remark like "%' . $data['remark'] . '%"';
        }

        $list_count = Yii::$app->db->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'st.id' : 'st.' . $data['columns'][$data['order'][0]['column']]['data'];
        $sql .= ' ORDER BY ' . $sort_string . ' ' . ($data['order'][0]['dir'] == 'asc' ? 'asc' : 'desc');
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        //操作日志
        $this->saveLog($this->service, '入库单查询', 'VIEW', '获取物料列表' . "\r\n" . \yii\helpers\Json::encode($list));
        return \yii\helpers\Json::encode($result);
    }

    //ajax作废、审核
    public function actionEditStockStatus()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['status']) || !isset($data['stockNo']) || !in_array($data['status'], array('1', '9')) || empty($data['stockNo'])) {
            $this->retJson('操作失败', 500);
        }

        $model = new StockTmp();
        $sql = "SELECT * FROM j_stock_tmp WHERE stockNo = '" . $data['stockNo'] . "'";
        $stock = Yii::$app->db->createCommand($sql)->queryOne();
        if ($stock && $stock['stockStatus'] != 0) {
            $this->retJson('单据状态异常，请刷新后重试', 500);
        }

//        if($stock['purchaseOrderNo'] && !empty($stock['purchaseOrderNo'])){
//
//            $sql = "SELECT status FROM j_purchase_order WHERE orderNo = '" . $stock['purchaseOrderNo'] . "'";
//            $res = Yii::$app->db->createCommand($sql)->queryOne();
//            if (!$res || $res['status'] != 1) {
//                $this->retJson('采购订单['.$stock['purchaseOrderNo'].']已关闭', 500);
//            }
//        }


        $stock['stockStatus'] = $data['status'];
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if ($data['status'] == 1) {
                $stock['reviewer'] = $model->getCreator();
                $stock['actualDate'] = date('Y-m-d');
            }
            $model::updateAll($stock, "stockNo=:stockNo", array(':stockNo' => $data['stockNo']));
            $transaction->commit();
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }

//ajax入库单-物料查询
    public function actionGetMaterielList()
    {
        $data = Yii::$app->request->post();

        $sql = '';
        $sql_list = 'SELECT ma.*,wh.warehouseName FROM j_materiel ma
        LEFT JOIN j_warehouse wh ON ma.warehouseId=wh.id WHERE 1=1';
        $sql_count = 'SELECT COUNT(0) CNT FROM j_materiel ma WHERE 1=1';

        $condition = $where = array();
        $searchKey = isset($data['searchKey']) ? trim($data['searchKey']) : '';
        //搜索关键字
        if (!empty($searchKey)) {
            $sql .= ' And (ma.materielName like "%' . $searchKey . '%"  OR ma.materielCode like "%' . $searchKey . '%")';
        }

        //所属仓库
        if (!empty($data['warehouseId'])) {
            $sql .= ' AND ma.warehouseId=' . $data['warehouseId'];
        }

        //是否管库存
        if (isset($data['storeFlg']) && !empty($data['storeFlg'])) {
            $sql .= ' AND ma.storeFlg=' . $data['storeFlg'];
        }

        if (isset($data['supplierId']) && !empty($data['supplierId'])) {
            $sql .= ' AND FIND_IN_SET(' . $data['supplierId'] . ',ma.supplierId)';
        }

        $sql .= ' And ma.useFlg = 1 ';

        $list_count = Yii::$app->db->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'ma.id' : 'ma.' . $data['columns'][$data['order'][0]['column']]['data'];
        $sql .= ' ORDER BY ' . $sort_string . ' ' . ($data['order'][0]['dir'] == 'asc' ? 'asc' : 'desc');
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db->createCommand($sql_list . $sql)->queryAll();
        if (!empty($list)) {
            //查询供应商
            foreach ($list as &$m) {
                $sql = 'SELECT id,supplierCode,supplierName FROM j_supplier WHERE id IN(' . $m['supplierId'] . ')';
                if (isset($data['supplierId']) && !empty($data['supplierId'])) {
                    $sql .= ' ORDER BY (CASE WHEN id=' . $data['supplierId'] . ' THEN 0 ELSE 1 END)';
                }
                $supplier = Yii::$app->db->createCommand($sql)->queryAll();
                $m['supplier'] = $supplier;
            }
        } else {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        //操作日志
        return \yii\helpers\Json::encode($result);
    }


    //ajax保存入库、损益单
    public function actionSaveStock()
    {
        $data = Yii::$app->request->post();

        if (!isset($data['materiels']) || !is_array($data['materiels']) || !isset($data['warehouseId'])) {
            $this->retJson('参数错误', 500);
        }

        $stock = array();
        $model = new StockTmp();
        $currentDate = date('Y-m-d H:i:s');
        $stock['warehouseId'] = $data['warehouseId'];
        $stock['purchaseOrderNo'] = isset($data['purchaseOrderNo']) && !empty($data['purchaseOrderNo']) ? $data['purchaseOrderNo'] : null;
        $stock['expecteDate'] = (isset($data['expecteDate']) && !empty($data['expecteDate'])) ? $data['expecteDate'] : null;
        $stock['remark'] = isset($data['remark']) ? $data['remark'] : '';
        $stock['sType'] = (isset($data['sType']) && in_array($data['sType'], array('0', '1'))) ? $data['sType'] : 0;

        $totalQty = 0;
        $totalAmount = 0;
        $stockDtl = array();

        if (isset($data['stockNo']) && !empty($data['stockNo'])) {
            $stockNo = $data['stockNo'];
        } else {
            $stockNo = ($data['sType'] == '0' ? 'R' : 'S') . date('YmdHis');
        }
        $stock['stockNo'] = $stockNo;

        if (isset($data['materiels']) && is_array($data['materiels'])) {

            foreach ($data['materiels'] as $m) {

                if ($data['sType'] == '0') {
                    /*
                     * 入库单 生成批次号
                     * 检查历史物料库存数据
                     * 无相同物料时直接使用 【生产日期+'001'】
                     * 有相同物料，生产日期、供应商、仓库 不同 【生产日期+'001'】
                     * 有相同物料，生产日期、供应商、仓库 相同，价格不同 max批次号递增+1
                     */
                    $sql = "SELECT sd.batch,sd.price,sd.supplierId,st.warehouseId
                            FROM j_stock_dtl_tmp sd INNER JOIN j_stock_tmp st ON sd.stockNo=st.stockNo
                            WHERE st.sType=0
                            AND sd.materielId='" . $m['materielId'] . "' 
                            AND sd.productDate='" . $m['productDate'] . "' ORDER BY sd.batch DESC";
                    $ck_stock = Yii::$app->db->createCommand($sql)->queryAll();

                    if ($ck_stock) {
                        $batch = '';
                        foreach ($ck_stock as $stock_dtl) {
                            if ($stock_dtl['supplierId'] == $m['supplierId'] &&
                                $stock_dtl['warehouseId'] == $data['warehouseId'] &&
                                $stock_dtl['price'] == $m['price']) {
                                $batch = $stock_dtl['batch'];
                                break;
                            }
                        }
                        if ($batch == '') $batch = $ck_stock[0]['batch'] + 1;

                    } else {
                        //新增批次
                        $batch = date('Ymd', strtotime($m['productDate'])) . '001';
                    }
                } else {
                    $batch = $m['batch'];
                }

                $stockDtl[] = array(
                    'creator' => $model->getCreator(),
                    'createTime' => $currentDate,
                    'stockNo' => $stockNo,
                    'stockId' => isset($m['stockId']) ? $m['stockId'] : null,
                    'materielId' => $m['materielId'],
                    'supplierId' => $m['supplierId'],
                    'batch' => $batch,
                    'productDate' => $m['productDate'],
                    'safeDate' => isset($m['safeDate']) ? $m['safeDate'] : date('Y-m-d', strtotime($m['productDate'] . ' + ' . $m['safeDay'] . 'day')),
                    'price' => $m['price'],
                    'dType' => isset($m['dType']) ? $m['dType'] : 0,
                    'qty' => $m['amount'],
                    'amount' => round($m['price'] * $m['amount'], 4),
                );
                $totalQty += $m['amount'];
                $totalAmount += round($m['price'] * $m['amount'], 4);
            }
        }

        $stock['totalQty'] = $totalQty;
        $stock['totalAmount'] = $totalAmount;

        try {
            $transaction = Yii::$app->db->beginTransaction();

            if (isset($data['stockNo']) && !empty($data['stockNo'])) {
                $stock['editor'] = $model->getCreator();
                $stock['editTime'] = $currentDate;
                $sql = "DELETE FROM j_stock_dtl_tmp WHERE stockNo='" . $data['stockNo'] . "'";
                Yii::$app->db->createCommand($sql)->execute();
                $model::updateAll($stock, "stockNo=:stockNo", array(':stockNo' => $stockNo));
            } else {
                $stock['creator'] = $model->getCreator();
                $stock['createTime'] = $currentDate;
                $stock['stockStatus'] = 0;
                Yii::$app->db->createCommand()->insert('j_stock_tmp', $stock)->execute();
            }
            foreach ($stockDtl as $dtl) {
                Yii::$app->db->createCommand()->insert('j_stock_dtl_tmp', $dtl)->execute();
            }

            $transaction->commit();
            $this->retJson('保存成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            Yii::error($e->getMessage());
            $this->retJson('操作失败', 500);
        }

    }


}